package com.css.fxfzdzzh.modules.mapManagement.repository;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.modules.mapManagement.entity.MapTemplate;
import com.css.fxfzdzzh.modules.mapManagement.param.MapTemplateQueryParam;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import com.css.fxfzdzzh.zcpt.sys.service.SysRoleService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年05月17日  16:54
 */
@Repository
public class MapTemplateRepository {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Resource
    SUserService sUserService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    SysAreaService sysAreaService;

    public void saveMap(MapTemplate map) {
        String sql =
                "insert into dzzh_map_template("
                        + "dmt_id,"
                        + "map_template_name,"
                        + "map_template_desc,"
                        + "map_level1_category,"
                        + "map_level2_category,"
                        + "attachment_id,"
                        + "upload_user_id,"
                        + "upload_user_name,"
                        + "upload_time,del_flag,sm_template_name) values(:dmtId, :mapTemplateName, :mapTemplateDesc, :mapLevel1Category, :mapLevel2Category, :attachmentId, "
                        + ":uploadUserId, :uploadUserName, :uploadTime,:delFlag,:smTemplateName) ";
        SqlParameterSource source = new BeanPropertySqlParameterSource(map);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedParameterJdbcTemplate.update(sql, source, keyHolder);
    }

    public Map<String, Object> mapTemplatePage(MapTemplateQueryParam param, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("");
        StringBuilder countSql = new StringBuilder("");
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, java.util.Map.class);
        for (java.util.Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode")).append(",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.DZZH_COUN_GL_ROLE)) {
            //国家级管理员 查看所有
            sql.append("select * from dzzh_map_template where del_flag='0' ");
            countSql.append("select count(*) from dzzh_map_template where del_flag='0' ");
        }else if (roles.contains(FxfzConstants.DZZH_COUN_YW_ROLE)) {
            //国家级业务人员可以查看图件分类为“地表破裂带评估-基础数据“”地表破裂带评估-评估结果”的
            sql.append("select * from dzzh_map_template where del_flag='0' and map_level1_category in ('8','9')");
            countSql.append("select count(*) from dzzh_map_template where del_flag='0' and map_level1_category in ('8','9')");
        }else if (roles.contains(FxfzConstants.DZZH_PRI_GL_ROLE)) {
            String areaName = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            //省管理员
            sql.append("select * from dzzh_map_template where del_flag='0' and map_level1_category not in ('8','9') and district like '%").append(areaName).append("%'");
            countSql.append("select count(*) from dzzh_map_template where del_flag='0' and map_level1_category not in ('8','9') and district like '%").append(areaName).append("%'");
        }else{
            //其他只能查看自己上传的
            sql.append("select * from dzzh_map_template where del_flag='0' and upload_user_id ='").append(userId).append("'");
            countSql.append("select count(*) from dzzh_map_template where del_flag='0' and upload_user_id ='").append(userId).append("'");
        }
        if (!PlatformObjectUtils.isEmpty(param.getMapTemplateName())) {
            sql.append(" and map_template_name like '%").append(param.getMapTemplateName()).append("%'");
            countSql.append(" and map_template_name like '%").append(param.getMapTemplateName()).append("%'");
        }
        if (!PlatformObjectUtils.isEmpty(param.getMapLevel1Category())) {
            sql.append(" and map_level1_category = '").append(param.getMapLevel1Category()).append("'");
            countSql.append(" and map_level1_category = '").append(param.getMapLevel1Category()).append("'");
        }
        if (!PlatformObjectUtils.isEmpty(param.getMapLevel2Category())) {
            sql.append(" and map_level2_category = '").append(param.getMapLevel2Category()).append("'");
            countSql.append(" and map_level2_category = '").append(param.getMapLevel2Category()).append("'");
        }
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;
        String sqlWhole = sql.append("  limit ").append(lastIndex).append(" offset ").append(firstIndex).toString();
        List<MapTemplate> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(MapTemplate.class));
        Integer total = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
        java.util.Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    public int delete(List<String> dmtIdList) {
        String sql = "update dzzh_map_template set del_flag='1',update_user_id='"+ PlatformSessionContext.getUserID()+"',update_time=now() where dmt_id in (:dmtIdList)";
        java.util.Map map = new HashMap(2);
        map.put("dmtIdList", dmtIdList);
        return namedParameterJdbcTemplate.update(sql, map);
    }

    public MapTemplate getById(String dmtId) {
        String sql = "select * from dzzh_map_template where del_flag='0' and dmt_id='"+dmtId+"'";
        List<MapTemplate> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MapTemplate.class));
        return PlatformObjectUtils.isNotEmpty(query)?query.get(0):null;
    }

    public MapTemplate getByAttachId(String attachId) {
        String sql = "select * from dzzh_map_template where del_flag='0' and attachment_id='"+attachId+"'";
        List<MapTemplate> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MapTemplate.class));
        return PlatformObjectUtils.isNotEmpty(query)?query.get(0):null;
    }
}
